package cn.gailvlun.gll.presentation.apartment.room;

import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.github.markzhai.recyclerview.BindingViewHolder;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.gailvlun.gll.R;
import cn.gailvlun.gll.chatlib.db.ChatDB2;
import cn.gailvlun.gll.chatlib.event.MessageEvent;
import cn.gailvlun.gll.chatlib.message.Message;
import cn.gailvlun.gll.chatlib.message.MessageType;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.QueryParam;
import cn.gailvlun.gll.presentation.apartment.room.vm.InviteFriendViewModel;
import cn.gailvlun.gll.presentation.base.BaseActivity;
import cn.gailvlun.gll.databinding.ActivityInviteFriendBinding;
import cn.gailvlun.gll.databinding.ItemInviteFriendBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.Member;
import cn.gailvlun.gll.net.apartment.member.AddMemberReq;
import cn.gailvlun.gll.net.apartment.room.Room;
import cn.gailvlun.gll.net.base.Profile;
import cn.gailvlun.gll.presentation.apartment.room.adapter.InviteFriendAdapter;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.ProfileUtil;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.ToastUtil;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.reactivex.functions.Consumer;
import io.realm.Realm;


public class InviteFriendActivity extends BaseActivity implements OnRefreshListener, OnLoadmoreListener{

    public static void openActivity(Context context, final Room room) {
        Intent intent = new Intent(context, InviteFriendActivity.class);
        intent.putExtra("roomId", room.getId());
        Realm realm = Realm.getInstance(ChatDB2.INSTANCE.getConfiguration());
        realm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                realm.insertOrUpdate(room);
            }
        });
        realm.close();

        context.startActivity(intent);
    }

    private ActivityInviteFriendBinding mBinding;
    private InviteFriendAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;

    @Override
    protected void initComponent() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_invite_friend);

        mAdapter = new InviteFriendAdapter(mContext);
        mAdapter.setPresenter(new Presenter());
        mBinding.recyclerView.setAdapter(mAdapter);

        mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recyclerView.setLayoutManager(mLayoutManager);

        mBinding.srl.setOnRefreshListener(this);
        mBinding.srl.setOnLoadmoreListener(this);
        mBinding.srl.setEnableLoadmore(false);
    }

    private InviteFriendViewModel mViewModel;

    @Override
    protected void createHandler() {
        mBinding.nbv.setOnBackListener(new NavigationBarView.OnBackListener() {
            @Override
            public void onBack(NavigationBarView nb) {
                onBackPressed();
            }
        });
    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        final int roomId = getIntent().getIntExtra("roomId", -1);
        if (roomId == -1) {
            finish();
        }
        mViewModel = ViewModelProviders.of(this).get(InviteFriendViewModel.class);
        mViewModel.getInviteRoom(roomId);

        mAdapter.setDecorator(new BaseViewAdapter.Decorator() {
            @Override
            public void decorator(BindingViewHolder holder, int position, int viewType) {
                ItemInviteFriendBinding itemBinding = (ItemInviteFriendBinding) holder.getBinding();
                Profile profile = itemBinding.getItem();
                if (!IsEmpty.list(profile.getInvites())) {
                    for (Room room : profile.getInvites()) {
                        if (room.getId() == roomId) {
                            itemBinding.tvInvite.setEnabled(false);
                            itemBinding.tvInvite.setText("已邀请");
                            break;
                        }
                    }
                }
            }
        });

        mBinding.srl.autoRefresh(0);
    }

    private QueryParam mQueryParam = new QueryParam();

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mQueryParam.resetPage();
        HttpMethods.getFriendService()
                .getFriends(mQueryParam.getPage())
                .compose(RxUtil.<ListRes<Profile>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Profile>>() {
                    @Override
                    protected void onSuccess(ListRes<Profile> response) {
                        loadRecyclerView(response.getResults(), true, response.isNext());
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Profile> response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        mBinding.srl.finishRefresh();
                    }
                });
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mQueryParam.nextPage();
        HttpMethods.getFriendService()
                .getFriends(mQueryParam.getPage())
                .compose(RxUtil.<ListRes<Profile>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Profile>>() {
                    @Override
                    protected void onSuccess(ListRes<Profile> response) {
                        loadRecyclerView(response.getResults(), false, response.isNext());
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Profile> response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                    }

                    @Override
                    protected void onFinish() {
                        super.onFinish();
                        mBinding.srl.finishLoadmore();
                    }
                });
    }

    private void loadRecyclerView(List<Profile> profiles, boolean isRefresh, boolean isMore) {
        if (isRefresh) {
            if (IsEmpty.list(profiles)) {
                mAdapter.clear();

            } else {

                mAdapter.set(profiles);

            }
        } else {
            mAdapter.addAll(profiles);

        }

        mBinding.srl.setEnableLoadmore(isMore);
    }

    public class Presenter implements BaseViewAdapter.Presenter {
        public void onInvite(final Profile item) {
            
            HttpMethods.getMemberService()
                    .addMember(new AddMemberReq(mViewModel.getInviteRoom().getId(), item.getId()))
                    .compose(RxUtil.<Member>applyScheduler())
                    .subscribe(new HttpSubscriber<Member>() {
                        @Override
                        protected void onSuccess(Member response) {
                            ToastUtil.showShort("邀请成功");

                            mAdapter.notifyDataSetChanged();

                            
                            final Message roomInviteMsg = Message.invite(mViewModel.getInviteRoom(), new Date(), ProfileUtil.getProfile(), "user:" + item.getId());
                            ChatDB2.INSTANCE.save(item);
                            ChatDB2.INSTANCE.saveMsg(roomInviteMsg);

                            RxUtil.timer(100, TimeUnit.MILLISECONDS)
                                    .subscribe(new Consumer<Long>() {
                                        @Override
                                        public void accept(Long aLong) throws Exception {
                                            EventBus.getDefault().post(new MessageEvent(roomInviteMsg.getId(), roomInviteMsg.getDialogId()));
                                        }
                                    });
                        }

                        @Override
                        protected void onFailure(String errMsg, @Nullable Member response, int code) {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    });
        }
    }
}
